from multiprocessing import Process, Queue, JoinableQueue
import time
import random


def producer(name, food, q):
    for i in range(10):
        data = '%s生产了%s%s' % (name, food, i)
        time.sleep(random.randint(1, 3))
        print(data)
        q.put(data)


def consumer(name, q):
    while True:
        food = q.get()
        if food is None: break
        time.sleep(random.randint(1, 3))
        print(f'{name} 吃了 {food}')
        q.task_done()  # 告诉队列你已经从里面祛除了一个数据并且处理完毕了


if __name__ == '__main__':
    # q = Queue()
    q = JoinableQueue()
    p1 = Process(target=producer, args=('大厨egon', '包子', q))
    p2 = Process(target=producer, args=('马叉虫tank', '泔水', q))
    c1 = Process(target=consumer, args=('春哥', q))
    c2 = Process(target=consumer, args=('新哥', q))
    p1.start()
    p2.start()
    c1.daemon = True
    c2.daemon = True
    c1.start()
    c2.start()

    p1.join()
    p2.join()
    # 等待生产者生产完毕之后 往队列中添加特定的结束符号
    # q.put(None)
    # q.put(None)
    q.join()  # 等待队列中所有的数据被取完再执行下面的代码

